package com.example.wendao.view.ui.fragment;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.model.entity.User;
import com.example.wendao.model.service.UserService;
import com.example.wendao.viewmodel.UserViewModel;

public class LoginFragment extends Fragment {

    public Button back_to_mine;
    public EditText log_username;
    public EditText log_password;

    public Button to_login;
    public Button to_register;

    private UserViewModel userViewModel;

    public LoginFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_login, container, false);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);

        back_to_mine = view.findViewById(R.id.back_to_mine);
        log_username = view.findViewById(R.id.log_username);
        log_password = view.findViewById(R.id.log_password);
        to_login = view.findViewById(R.id.to_login);
        to_register = view.findViewById(R.id.to_register);


        back_to_mine.setOnClickListener(view13 -> Navigation.findNavController(view).navigate(R.id.action_loginFragment_to_fragment_my));

        to_register.setOnClickListener(view12 -> Navigation.findNavController(view).navigate(R.id.action_loginFragment_to_registerFragment));
        to_login.setOnClickListener(view1 -> {
            //这里应该传入username看看有无名字，没有出一个提示用户名不存在，去注册或者用户名错误
            if(!userViewModel.checkUsername(log_username.getText().toString().trim())){
                Toast.makeText(getActivity(), "用户名不存在，请重新输入正确的或者去注册此用户名吧~", Toast.LENGTH_SHORT).show();
            }
            //用username去找password看看与填写的一不一样
            else if (userViewModel.login(log_username.getText().toString().trim(),log_password.getText().toString().trim())==null)
            {Toast.makeText(getActivity(), "用户名或密码不正确", Toast.LENGTH_SHORT).show();}
            //如果合适应该专区my页面然后需不需要穿什么参数
            else
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("亲爱的闻道道友：");
                builder.setMessage("恭喜您已经登录成功啦，快去开始自己的快乐旅程吧！");
                builder.setPositiveButton("确定", (dialogInterface, i) -> Navigation.findNavController(view1).navigate(R.id.action_loginFragment_to_fragment_my));
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
        return view;
    }
}